package com.ruoyi.ipms_patent.service.impl;

import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.RabbitMQConstants;
import com.ruoyi.common.core.rabbitmq.EmailMQSender;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.IPMSUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ipms_crm.entity.Customer;
import com.ruoyi.ipms_patent.dto.*;
import com.ruoyi.ipms_patent.entity.IpmsCase;
import com.ruoyi.ipms_patent.entity.OfficialInfo;
import com.ruoyi.ipms_patent.mapper.*;
import com.ruoyi.ipms_patent.rabbitmq.Email;
import com.ruoyi.ipms_patent.service.ContractService;
import com.ruoyi.ipms_patent.service.IpmsCaseService;
import com.ruoyi.ipms_patent.service.OfficialInfoService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author: isBao
 * Description:TODO:案件Service实现类
 */

@Service
public class IpmsCaseServiceImpl implements IpmsCaseService {

    @Resource
    IpmsCaseMapper ipmsCaseMapper;

    @Resource
    IpmsCaseBaseInfoMapper ipmsCaseBaseInfoMapper;

    @Resource
    ContractService contractService;

    @Resource
    CaseHistoryMapper caseHistoryMapper;

    /* 客户模块--这里就没有走feign了 */
    @Resource
    CrmCustomerMapper crmCustomerMapper;

    /* 邮箱mapper */
    @Resource
    private EmailMQSender emailMQSender;

    @Resource
    CrmContractMapper crmContractMapper;


    /* 基于用户角色返回对应的案件列表 */
    @Override
    public List<IpmsCaseBaseInfo> findCaseByuserId(IpmsCaseBaseInfo ipmsCaseBaseInfo) {

        //1.获取当前登录用户对应角色和id，来获取对应状态的案件列表   用户角色---可查看案件（基于状态：待分配（0）、撰稿（1）、撰稿完成（2）、审核等）
        Set<String> rolesList = SecurityUtils.getLoginUser().getRoles();

        //获取登录用户id
        int userId = new Long(SecurityUtils.getUserId()).intValue();

        //定义一个案件状态list
        Set<String> caseStatus = new HashSet<>();
        caseStatus.add("-1");

        //2.判断角色
        //将角色能看到的案件状态记在集合caseStatus中---根据字典数据
        /* 案件状态：0-未分配  1-撰稿中  2-撰稿完成  3-初审  4-复审  5-内部驳回  6-撤销  7-提交官方  8-官方驳回  9-已结案 */
        String caseTab = ipmsCaseBaseInfo.getCaseTab();
        //判断前端是否有选页面操作，有就找对应状态案件
        if(caseTab != null && caseTab != ""){
            if(caseTab.equals("待分配")){
                caseStatus.add("0");
            }else if(caseTab.equals("已分配")){
                caseStatus.add("1");
            }else if(caseTab.equals("驳回")){
                caseStatus.add("5");
                caseStatus.add("8");
            }

            for(String role : rolesList){
                if(role.equals("salesman")){
                    ipmsCaseBaseInfo.setCaseEmpSalesId(userId);
                }else if(role.equals("writer")){
                    ipmsCaseBaseInfo.setCaseEmpWriterId(userId);
                }
            }
        }else{
            //没有选页面操作，判断是否有传案件状态id，有就按此id查询
            if(ipmsCaseBaseInfo.getCaseStatusId() != null && ipmsCaseBaseInfo.getCaseStatusId() != ""){
                caseStatus.add(ipmsCaseBaseInfo.getCaseStatusId());
            }else {
                //既没有选页面，也没有传状态id，则按角色分配其能可见的案件状态
                for(String role : rolesList){
                    if(role.equals("salesman")){
                        ipmsCaseBaseInfo.setCaseEmpSalesId(userId);
                        caseStatus.add("0");
                        caseStatus.add("1");
                        caseStatus.add("2");
                        caseStatus.add("3");
                        caseStatus.add("4");
                        caseStatus.add("5");
                        caseStatus.add("6");
                        caseStatus.add("7");
                        caseStatus.add("8");
                        caseStatus.add("9");
                    }else if(role.equals("writer")){
                        ipmsCaseBaseInfo.setCaseEmpWriterId(userId);
                        caseStatus.add("1");
                        caseStatus.add("2");
                        caseStatus.add("3");
                        caseStatus.add("4");
                    }else if(role.equals("manager")){
                        caseStatus.add("3");
                    }else if(role.equals("boss")){
                        caseStatus.add("4");
                    }else if(role.equals("admin")){
                        caseStatus.add("0");
                        caseStatus.add("1");
                        caseStatus.add("2");
                        caseStatus.add("3");
                        caseStatus.add("4");
                        caseStatus.add("5");
                        caseStatus.add("6");
                        caseStatus.add("7");
                        caseStatus.add("8");
                        caseStatus.add("9");
                    }
                }
            }
        }


        //基于用户角色查找其能获取的案件列表
        return ipmsCaseBaseInfoMapper.selectCaseBaseInfoByuserId(ipmsCaseBaseInfo,caseStatus);

    }

    /* 案件新增 */
    @Override
    public int insertCase(List<String> contractNos) {

        IpmsCase ipmsCase = new IpmsCase();
        ContractDto contractDto = new ContractDto();

        for(String contractNo : contractNos){
            //1.根据合同号查询合同id,业务员id---模拟
            contractDto.setContractNo(contractNo);
            List<ContractDto> contractDtos = contractService.selectcontractList(contractDto);
            //合同id
            int contractId = contractDtos.get(0).getContractId();

            //业务员id
            int empId = contractDtos.get(0).getEmpId();

            //2.新增案件
            ipmsCase.setCaseNo(IPMSUtils.spawnNo("CASE.",5));
            ipmsCase.setContractId(contractId);
            ipmsCase.setCaseEmpSalesId(empId);
            ipmsCaseMapper.insertCase(ipmsCase);

            //3.插入案件新增历史记录
            caseHistoryMapper.insertCaseHistory(ipmsCase.getCaseId(),"0");

        }
        return 1;
    }

    /* 案件修改 */
    @Override
    public int updateCase(IpmsCaseModify ipmsCaseModify) {
        //目前只考虑案件状态修改---随流程，人员变更暂不考虑
        //
        IpmsCase ipmsCase = new IpmsCase();
        List<String> caseNos = new ArrayList<>(ipmsCaseModify.getCaseNos());

        /* 案件状态：0-未分配  1-撰稿中  2-撰稿完成  3-初审  4-复审  5-内部驳回  6-撤销  7-提交官方  8-官方驳回  9-已结案 */

        //获取前端操作
        String caseOperation = ipmsCaseModify.getCaseOperation();
        if(caseOperation.equals("分配撰稿人")){
            ipmsCase.setCaseStatusId("1");
        }else if(caseOperation.equals("撰稿人提交")){
            ipmsCaseModify.setCaseReasonsRejection("/");
            ipmsCase.setCaseStatusId("3");
        }else if(caseOperation.equals("撰稿人申请变更")){
            ipmsCaseModify.setCaseEmpWriterId(0);
            ipmsCase.setCaseStatusId("0");
        }else if(caseOperation.equals("初审批准")){
            ipmsCase.setCaseStatusId("4");
        }else if(caseOperation.equals("复审批准")){
            ipmsCase.setCaseStatusId("7");
        }else if(caseOperation.equals("内部驳回")){
            ipmsCase.setCaseStatusId("5");
        }else {

        }

        //设置业务员、撰稿人、案件状态、原因
        ipmsCase.setCaseEmpSalesId(ipmsCaseModify.getCaseEmpSalesId());
        ipmsCase.setCaseEmpWriterId(ipmsCaseModify.getCaseEmpWriterId());
        ipmsCase.setCaseReasonsRejection(ipmsCaseModify.getCaseReasonsRejection());

        return ipmsCaseMapper.updateCase(ipmsCase,caseNos);
    }

    /* 案件删除---修改状态 */
    @Override
    public int delCaseByCaseNo(List<String> caseNos) {
        return ipmsCaseMapper.delCaseByCaseNo(caseNos);
    }


    /* 案件编号单个查询 */
    @Override
    public IpmsCaseBaseInfo selectCaseByCaseNo(String caseNo) {
        return ipmsCaseBaseInfoMapper.selectCaseByCaseNo(caseNo);
    }

    /* 案件编号单个查询之申请文件 */
    @Override
    public List<IpmsCaseBaseInfoB> selectCaseBByCaseNo(String caseNo) {
        List<IpmsCaseBaseInfoB> ipmsCaseBaseInfoBList=ipmsCaseBaseInfoMapper.selectCaseBCyCaseNo(caseNo);
        String caseStatusId=ipmsCaseBaseInfoMapper.selectCaseBCyCaseNo(caseNo).get(0).getCaseStatusId();
        if (caseStatusId !=null && caseStatusId !="" && caseStatusId.equals("3")){
            String reviewerName=ipmsCaseBaseInfoMapper.selectReviewerByCaseStatusId(caseStatusId).get(0).getReviewerName();
            ipmsCaseBaseInfoBList.get(0).setReviewerName(reviewerName);
        }else if (caseStatusId !=null && caseStatusId !="" && caseStatusId.equals("4")){
            String reviewerName=ipmsCaseBaseInfoMapper.selectReviewerBByCaseStatusId(caseStatusId).get(0).getReviewerName();
            ipmsCaseBaseInfoBList.get(0).setReviewerName(reviewerName);
        }else if (caseStatusId !=null && caseStatusId !="" && caseStatusId.equals("7")){
            String reviewerName="官方";
            ipmsCaseBaseInfoBList.get(0).setReviewerName(reviewerName);
        }else{
            String reviewerName="暂无";
            ipmsCaseBaseInfoBList.get(0).setReviewerName(reviewerName);
        }
        return ipmsCaseBaseInfoBList;
    }

    @Override
    public List<IpmsCaseBaseInfoD> selectOfficalByCaseNo(String caseNo) {
        return ipmsCaseBaseInfoMapper.selectOfficalByCaseNo(caseNo);
    }


    @Resource
    OfficialInfoMapper mapper;
    //OfficialInfoService officialInfoService;

    /* 模拟官方审核 */
    @Override
    public int officialResult() {

        /* 案件状态：0-未分配  1-撰稿中  2-撰稿完成  3-初审  4-复审  5-内部驳回  6-撤销  7-提交官方  8-官方驳回  9-已结案 */

        //获取案件列表中所有已提交官方的案件id
        List<Integer> caseList = ipmsCaseMapper.selectCaseToOfficial();
        if(caseList.size() == 0){
            return 0;
        }

        String caseStatusId = "";
        int i = 0;
        //随机返回结果模拟官方回复案件状态
        for(int caseId : caseList){
            //8-官方驳回  9-已结案
            //生成随机状态
            i = Math.random() > 0.5 ? 8 : 9;
            caseStatusId = i+"";

            //模拟官方回复后修改状态
            if(i != 0){

                /*根据官方回复修改案件、合同状态并向客户发送消息*/

                /* 1.获取合同和客户信息 */
                //通过案件id获取客户id和合同id（contractCaseId封装客户id和合同id）
                ContractCaseDto contractCaseId = ipmsCaseMapper.findContractCaseId(caseId);

                //客户id查客户拿去邮箱地址
                CrmCustomerDto crmCustomerDto = crmCustomerMapper.selectCustomerById(contractCaseId.getCustomerId());
                System.out.println("客户id和邮箱"+crmCustomerDto);
                //判空
                if(crmCustomerDto != null){
                    //2.判断是通过还是驳回，修改对应状态、消息、案件驳回原因记录
                    //定义邮箱消息、案件驳回原因
                    String msg = "";
                    String caseReasonsRejection = "/";

                    //2.1 官方通过
                    if(caseStatusId.equals("9")){
                        //官方审核通过
                        msg ="あなたの特許は成功しました,客户您好：您的专利申请成功，Congratulation";

                        //案件历史记录--完结
                        caseHistoryMapper.insertCaseHistory(caseId,"8");

                        //合同id修改合同状态
                        crmContractMapper.updateContractToOver(contractCaseId.getContractId());

                        // 客户信息修改
                        //通过案件id找到客户id，然后客户办案次数+1，客户状态置为完结
                        crmCustomerMapper.updatExperienceAndStatus(crmCustomerDto.getCustomerId());

                    }else {
                        //2.2 官方驳回，撰稿池页面显示，可以重新分配撰稿人
                        msg ="あなたの特許出願は失敗しました,客户您好：您的专利申请失败，Sorry";
                        caseReasonsRejection = "不符合行业规范！！！";
                        //案件历史记录--官方驳回
                        caseHistoryMapper.insertCaseHistory(caseId,"9");
                    }

                    //无论通过还是驳回都要修改案件状态和发送邮箱
                    //修改案件状态
                    ipmsCaseMapper.officialReply(caseId,caseStatusId,caseReasonsRejection);

                    //3.发送邮件通知客户
                    //收件人
                    List<String> emailList = new ArrayList<String>(){{
                        add("1678880940@qq.com");
                        add("1027300528@qq.com");
                        add("2799408633@qq.com");
                        add("1028246845@qq.com");
                        //add("547514399@qq.com");
                        add("748118234@qq.com");
                        add("1310815606@qq.com");
                        add(crmCustomerDto.getCustomerEmail());
                    }};
                    String[] emailArray = emailList.stream().toArray(String[]::new);
                    //内容
                    String ctx = "新しい情報がありますのでご査収ください ";
                    ctx = msg;
                    emailMQSender.send(RabbitMQConstants.EMAIl_EXCHANGE,"ipms.email.patent",
                            new Email(emailArray,ctx));

                    //4.插入官文通知
                    OfficialInfo info =  new OfficialInfo();
                    info.setOfficalInformationTypeId("1");
                    info.setCaseId(caseId);
                    info.setOfficalInformationDocument(msg);
                    info.setCreateTime(DateUtils.getNowDate());
                    info.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
                    info.setCreateTime(DateUtils.getNowDate());
                    mapper.insertOne(info);
                }
            }
        }

        return 1;
    }
}
